package co.recloud.ariadne.thread;

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

import co.recloud.ariadne.model.Host;
import co.recloud.ariadne.request.PingRequest;
import co.recloud.ariadne.response.Response;
import co.recloud.ariadne.store.HostTable;

public class RecoveryThread implements Runnable {
	public synchronized void run() {
		while(true) {
			if(!Main.waitForServiceStatus()) {
				continue;
			}
			if(!Main.waitForIdle()) {
				continue;
			}
			HostTable ht = HostTable.getInstance();
			Host replica = ht.getRecoveryReplica();
			PingRequest request = new PingRequest();
			Queue<Response> responses = new ConcurrentLinkedQueue<Response>();
			Semaphore semaphore = new Semaphore(0);
			request.setTarget(replica);
			try {
				boolean responded = semaphore.tryAcquire(1, TimeUnit.SECONDS);
				if(!responded) {
					initiateRecovery(replica);
				}
				
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				wait(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				break;
			}
		}
	}

	private void initiateRecovery(Host replica) {
		HostTable ht = HostTable.getInstance();
		ht.recoverGrid(replica);
	}
}
